﻿var chooseClonum = [];
var clonumData = [];
// 注册
Vue.component('qdt-table-component', {
    props: {
        //data: Array,
        columns: Array,
        contentHeight: Number,
        url: String,
        tableName: String, //js文件名+table名（缓存tableHeader 的隐藏显示）
        dataCallback: {
            default: null,
            type: Function
        },
        formSubmit: {
            type: Boolean,
            default: false
        },
        selectionChange: {
            default: null,
            type: Function
        },
        isPaging: {
            default: true,
            type: Boolean
        }
    },
    data: function () {
        const generateData = _ => {
            var clonumData = this.columns;
            for (let i = 0; i < clonumData.length; i++) {
                if (!clonumData[i].isLink) {
                    clonumData[i].isLink = false;//默认不是link
                }
                if (!clonumData[i].isHide) {
                    clonumData[i].isHide = false;//默认显示
                }
                if (!clonumData[i].splitStr) {
                    clonumData[i].splitStr = ',';//默认显示
                }
                if (clonumData[i].ableSort == null) {
                    clonumData[i].ableSort = false;//默认显示
                }
                clonumData[i].sort = i;
            }
            return clonumData;
        };

        return {
            //url: ""
            incolumns: generateData(),
            data: [],
            total: 0,
            pageSize: 10,
            page: 1,
            loading: false,
            postData: {},
            editshow: false,
            transfer_data: clonumData,
            transfer_setting: chooseClonum,
            title: ["隐藏字段", "显示字段"],
            chooseKey: [],
            orderProp: '',
            orderType: '',
            allDatas: []
        }
    },
    methods: {
        loadData(data) {
            this.loading = true;
            let vm = this;
            if (!this.isPaging) {//假分页
                var start = (this.page - 1) * this.pageSize;
                this.data = this.allDatas.slice(start, start + this.pageSize);
                vm.loading = false;
                this.dataCallback(this.data);
                return;
            }
            if (data != null) {
                this.postData = data;
                this.postData.Page = this.page;
                this.postData.PageSize = this.pageSize;
            }
            if (this.formSubmit) {
                $("#formSearch").ajaxSubmit({
                    url: this.url,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        __RequestVerificationToken: getToken(),
                        PageSize: vm.pageSize,
                        Page: vm.page,
                        OrderProp: vm.orderProp,
                        OrderType: vm.orderType
                    },
                    beforeSubmit: function () {
                        return true;
                    },
                    success: function (response) {
                        if (response.ResultType == 0) {
                            if (vm.dataCallback != null)
                                vm.dataCallback(response);
                            vm.data = response.DataObj;
                            vm.total = response.Total;
                        } else {
                            alterMsg.alterError(response.Msg);
                        }
                        vm.loading = false;
                    },
                    error: function (error) {
                        alterMsg.alterError(error);
                        vm.loading = false;
                    }
                });
            }
            else {
                qdtPost({
                    method: 'post',
                    url: this.url,
                    data: this.postData
                }).then(function (response) {
                    if (vm.dataCallback != null)
                        vm.dataCallback(response);
                    var tableData = response.data;
                    if (tableData.ResultType == 0) {
                        vm.data = tableData.DataObj;
                        vm.total = tableData.Total;
                    } else {
                        alterMsg.alterError(tableData.Msg);
                    }
                    vm.loading = false;
                }).catch(function (error) {
                    alterMsg.alterError(error);
                    vm.loading = false;
                });
            }
        },
        getData() {
            return this.data;
        },
        handleSizeChange(val) {
            this.page = 1;
            this.pageSize = val;
            this.loading = true;
            this.loadData(this.postData);
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.page = val;
            this.loadData(this.postData);
        },
        showImage: function (imgSrc) {
            if (imgSrc == null || imgSrc == "") {
                return false;
            } else {
                return true;
            }
        },
        indexMethod(index) {
            return (this.page - 1) * this.pageSize + index + 1;
        },
        getImage(imageStr, splitStr) {
            if (imageStr != null && imageStr != "") {
                return imageStr.split(splitStr);
            }
            return [];
        },
        editClick() {
            this.editshow = !this.editshow;
            if (this.editshow) {
                this.resetClounm();
            }
        },
        renderheader(h, { column, $index }) {
            return h('span',
                {
                    style: "cursor: pointer; height: 35px; display: block;",
                    on: {
                        click: this.editClick
                    },
                    nativeOn: {
                        click: this.editClick
                    }
                }, column.label);
        },
        resetClounm() {
            this.transfer_data = [];
            this.transfer_setting = [];
            for (let i = 0; i < this.incolumns.length; i++) {
                this.transfer_data.push({
                    key: this.incolumns[i].prop,
                    label: this.incolumns[i].label,
                });
                if (this.incolumns[i].isHide != true) {
                    this.transfer_setting.push(this.incolumns[i].prop);
                }
            }
            var items = JSON.parse(window.localStorage.getItem(this.tableName || "[]"));
            if (items != null) {
                for (var i = 0; i < this.incolumns.length; i++) {
                    this.incolumns[i].isHide = items.indexOf(this.incolumns[i].prop) == -1 ? true : false;
                }
                this.transfer_setting = items;
            }
        },
        clounmChange(key) {
            this.chooseKey = [];
        },
        reload() {
            var newColunm = [];
            for (var i = 0; i < this.transfer_data.length; i++) {
                newColunm.push(this.getColByKey(this.transfer_data[i].key));
            }
            this.incolumns = newColunm;
            for (var i = 0; i < this.incolumns.length; i++) {
                this.incolumns[i].isHide = this.transfer_setting.indexOf(this.incolumns[i].prop) == -1 ? true : false;
            }
            window.localStorage.setItem(this.tableName, JSON.stringify(this.transfer_setting));
            this.editClick();
            //重新赋值（不然会导致 列交换后数据错误）
            var newData = [];
            newData = this.data;
            this.data = [];
            this.$nextTick(function () {
                this.data = newData;
            });
            //this.temp_clounm = [];
        },
        getColByKey(key) {
            for (var i = 0; i < this.incolumns.length; i++) {
                if (this.incolumns[i].prop == key)
                    return this.incolumns[i];
            }
        },

        adjustClick(type) {
            let newTransfer_data = [];
            var new_setting = [];
            var nextIndex = this.getSortByKey(type);
            if (nextIndex == -1 && type != 1)
                return;
            //index之前
            for (var i = 0; i <= nextIndex; i++) {
                if (this.chooseKey.indexOf(this.transfer_data[i].key) == -1) {
                    newTransfer_data.push(this.transfer_data[i]);
                }
            }
            // 需要下调的
            for (var i = 0; i <= this.chooseKey.length; i++) {
                for (var i = 0; i < this.transfer_data.length; i++) {
                    if (this.chooseKey.indexOf(this.transfer_data[i].key) != -1) {
                        newTransfer_data.push(this.transfer_data[i]);
                    }
                }
            }
            //index之后
            for (var i = nextIndex + 1; i < this.transfer_data.length; i++) {
                if (this.chooseKey.indexOf(this.transfer_data[i].key) == -1) {
                    newTransfer_data.push(this.transfer_data[i]);
                }
            }
            for (var i = 0; i < newTransfer_data.length; i++) {
                if (this.transfer_setting.indexOf(newTransfer_data[i].key) != -1)
                    new_setting.push(newTransfer_data[i].key);
            }
            this.transfer_data = newTransfer_data;
            this.transfer_setting = new_setting;
        },
        getSortByKey(type) {
            if (this.chooseKey.length == 0) {
                return -1;
            }
            var key = this.chooseKey[0];
            for (var i = 0; i < this.transfer_data.length; i++) {
                if (this.transfer_data[i].key == key) {
                    if (type == 1) {//上调
                        for (var j = i - 1; j >= 0; j--) {
                            if (this.chooseKey.indexOf(this.transfer_data[j].key) == -1 && this.transfer_setting.indexOf(this.transfer_data[j].key) != -1) {
                                return j - 1;
                            }
                        }
                        return -1;
                    } else {
                        for (var j = i + 1; j < this.transfer_data.length; j++) {//下调
                            if (this.chooseKey.indexOf(this.transfer_data[j].key) == -1 && this.transfer_setting.indexOf(this.transfer_data[j].key) != -1) {
                                return j;
                            }
                        }
                        return -1;
                    }
                }
            }
            return -1;
        },
        rightCheck(key) {
            this.chooseKey = key;
        },
        handleSelectionChange(val) {
            if (this.selectionChange != null)
                this.selectionChange(val);
        },
        handleCellClick(row) {
            this.$refs.table.toggleRowSelection(row);
        },
        handleDoubleClick(row, column, cell, event) {
            this.$emit('cell-dblclick', row);
        },
        handleSortChange(scope) {
            this.orderType = scope.order == "ascending" ? 'ASC' : 'DESC';
            this.orderProp = scope.prop;
            if (!this.isPaging) {
                if (scope.order == "ascending") {
                    this.allDatas.sort(function (a, b) {
                        return a[scope.prop] - b[scope.prop]
                    });
                } else {
                    this.allDatas.sort(function (a, b) {
                        return b[scope.prop] - a[scope.prop]
                    });
                }
            }
            this.loadData();
        }
    },
    created: function () {
        this.incolumns = this.columns;
    },
    mounted: function () {
        this.$nextTick(function () {
            this.resetClounm();
        });
    },
    template: ` <div>
        <el-table :data="data"
                  v-loading="loading"
                  ref="table"
                  stripe
                  border
                  :height="contentHeight"
                  style="width: 100%"
                  v-on:cell-click="handleCellClick"
                  v-on:selection-change="handleSelectionChange"
                  v-on:cell-dblclick="handleDoubleClick"
                  v-on:sort-change="handleSortChange">
            <el-table-column type="selection"
                             width="55"
                             v-if="selectionChange != null">
            </el-table-column>
            <el-table-column type="index"
                             width="50"
                             label="序号"
                             :index="indexMethod"
                             sortable>
            </el-table-column>
            <el-table-column v-for="(col, index) in incolumns"
                             :key="index"
                             :prop="col.prop"
                             :label="col.label"
                             :min-width="col.minWidth"
                             :formatter="col.formatter"
                             v-if="!col.isHide"
                             :sortable="col.ableSort"
                             :sort-method="col.sortMethod">
                <template slot-scope="scope">
                    <div v-if="col.isImage">
                        <img v-if="showImage(scope.row[col.prop])"
                             v-for="(src, img_index) in getImage(scope.row[col.prop], col.splitStr) "
                             :src="src"
                             v-on:click="col.method(img_index, scope.row)"
                             style="width:50px; height:50px; cursor: pointer; margin-top:2px; margin-right:2px;" />
                    </div>
                    <div v-else-if="col.isLink">
                        @*加载附加页面*@
                        <a v-on:click="col.method(index, scope.row)"
                           style="color: #246DB6;">
                            {{scope.row[col.prop]}}
                        </a>
                    </div>
                    <div v-else-if="col.formatter" v-html="col.formatter(index, scope.row, scope.row[col.prop])">
                        @*{{col.formatter(index, scope.row, scope.row[col.prop])}}*@
                    </div>
                    <div v-else>
                        {{scope.row[col.prop]}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column width="40"
                             label="..."
                             v-on:click="editClick()"
                             v-bind:render-header="renderheader">
            </el-table-column>
            <slot>

            </slot>
        </el-table>
        <el-pagination v-on:size-change="handleSizeChange"
                       background
                       v-on:current-change="handleCurrentChange"
                       :current-page="page"
                       v-bind:page-sizes="[10, 20, 50, 100]"
                       :page-size="pageSize"
                       layout="total , prev, pager, next, sizes"
                       :total="total">
        </el-pagination>

        <el-dialog title="编辑显示隐藏字段"
                   v-bind:visible.sync="editshow"
                   width="540px">
            <el-transfer v-model="transfer_setting"
                         v-bind:data="transfer_data"
                         v-on:change="clounmChange"
                         v-bind:titles="title"
                         v-on:right-check-change="rightCheck">
                <span class="transfer-footer" slot="left-footer"></span>
                <el-button class="transfer-footer" slot="right-footer" size="small" icon="el-icon-sort-up" v-on:click="adjustClick(1)">上移</el-button>
                <el-button class="transfer-footer" slot="right-footer" size="small" icon="el-icon-sort-down" v-on:click="adjustClick(2)">下移</el-button>
            </el-transfer>
            <span slot="footer" class="dialog-footer">
                <el-button type="info" v-on:click="editClick()">取 消</el-button>
                <el-button type="qprimary" v-on:click="reload()">确 定</el-button>
            </span>
        </el-dialog>
    </div>`
})
